/**
 * 
 */
package cn.agiledata.bank.common.service;

import java.util.Random;

import uk.ltd.getahead.dwr.WebContextFactory;

import cn.agiledata.bank.account.service.AccountSummary;
import cn.agiledata.bank.common.dao.IRandomCodeDAO;
import cn.agiledata.bank.common.util.Constant;



/**
 * @author 马贤波
 *
 * Apr 11, 2006
 */
public class CommonService  {
	
	public static final String SERVICE_NAME = "commonService" ;
	
	private static Random RAND = new Random () ;
	private IRandomCodeDAO dao ;
	
	public  String retrieveAlphaRandomCode (int digit, String regex, boolean unique) {
		
		
		StringBuffer content = new StringBuffer () ;
		
		int i = 0 ;
		while ( i < digit ) {
			byte[] tmp = new byte[1] ;
			
			RAND.nextBytes(tmp) ;
			String chr = new String(tmp) ;
			
			if (chr.matches(regex)) {
				content.append(chr) ;
				i ++ ;
			}
			
		}
		
		String result = content.toString() ;
		
		if (unique) {
			Object obj = dao.findRandomCode(result) ;
			if (obj != null) {
				return this.retrieveAlphaRandomCode(digit, regex, true) ;
			}
			
			dao.saveRandomCode(result) ;
		}
		
		return result ;
	}
	
	public  String retrieveAlphaRandomCode (int digit, String regex) {
		return this.retrieveAlphaRandomCode(digit, regex, false) ;
	}
	
	
	public void selectSubAccount (long subAccountId) {
		AccountSummary user = (AccountSummary) WebContextFactory.get()
				.getSession(true)
				.getAttribute(Constant.SESSION_ACCOUNT_SUMMARY);
	
		if (user != null) {
			user.setSelectedSubAccountId(subAccountId) ;
		}
	}
	

	/**
	 * @return Returns the dao.
	 */
	public IRandomCodeDAO getDao() {
		return dao;
	}

	/**
	 * @param dao The dao to set.
	 */
	public void setDao(IRandomCodeDAO dao) {
		this.dao = dao;
	}
	
	

	
}
